package com.haust.leyou.controller;

import com.haust.leyou.pojo.Brand;
import com.haust.leyou.service.BrandService;
import com.haust.leyou.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Auther: csp1999
 * @Date: 2020/12/08/19:53
 * @Description:
 */
@Controller
@RequestMapping("/brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    /**
     * 根据查询条件,查询品牌相关的数据信息,并分页有序展示
     *
     * @param key    key
     * @param page   页数
     * @param rows   每页的记录数
     * @param sortBy 排序
     * @param desc   排序方式
     * @return
     */
    @GetMapping("/page")
    public ResponseEntity<PageResult<Brand>> queryBrandsByPage(
            @RequestParam(value = "key", required = false) String key,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,
            @RequestParam(value = "sortBy", required = false) String sortBy,
            @RequestParam(value = "desc", required = false) Boolean desc) {

        PageResult<Brand> result = brandService.queryBrandsByPage(key, page, rows, sortBy, desc);

        // 判空
        if (CollectionUtils.isEmpty(result.getItems())) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 新增品牌
     *
     * @param brand
     * @param cids
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam("cids") List<Long> cids) {

//        System.out.println(brand);//Brand{id=null, name='Java编程思想', image='', letter=J}
        brandService.saveBrand(brand, cids);

        // 状态码201：创建成功！
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据分类cid 查询品牌列表
     *
     * @param cid
     * @return
     */
    @GetMapping("/cid/{cid}")
    public ResponseEntity<List<Brand>> queryBrandsByCid(@PathVariable("cid") Long cid) {

        List<Brand> brandList = brandService.queryBrandsByCid(cid);

        // 判空
        if (CollectionUtils.isEmpty(brandList)) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(brandList);
    }

    /**
     * 根据品牌id 查询品牌信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public ResponseEntity<Brand> queryBrandById(@PathVariable("id") Long id) {

        Brand brand = brandService.queryBrandById(id);

        if (brand == null) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(brand);
    }

}
